package com.sls.api.game.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.sls.api.game.constant.Constant;
import com.sls.api.game.pojo.EnfuServerInfo;
import com.sls.api.util.IpUtil;
import com.sls.api.util.PropertiesUtil;
import com.sls.api.util.UtilMD5Encryption;
import com.sls.core.socket.Head;
import com.sls.core.socket.SocketDTO;

/**
 * 
 * @Description：恩付订单结果异步通知
 * @author Wangxuegang
 * @Date：2013-5-25
 * 
 */
public class EnfuOrderStatusServlet extends SuperServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static Logger log = Logger.getLogger(EnfuOrderStatusServlet.class);

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setAttribute("org.eclipse.jetty.server.Request.queryEncoding",
				"GB2312");
		resp.setContentType("text/html;charset=GB2312");
		resp.setStatus(HttpServletResponse.SC_OK);

		// 商户号
		String merchantid = req.getParameter("merchantid");
		// 合作商的业务订单号
		String orderno = req.getParameter("orderno");
		// 订单结果
		String orderstatus = req.getParameter("orderstatus");
		// 充值时间
		String rechargetime = req.getParameter("rechargetime");
		// 原因
		String rechargeresult = req.getParameter("rechargeresult");
		if (rechargeresult != null && !("".equals(rechargeresult))) {
			rechargeresult = URLDecoder.decode(rechargeresult, "GB2312");
		}
		
		// 签名字符串
		String sign = req.getParameter("sign");
		log.info("恩付异步通知的参数：" + "merchantid:" + merchantid + "\n orderno:"
				+ orderno + "\n orderstatus:" + orderstatus + "\n rechargetime:"
				+ rechargetime + "\n rechargeresult:" + rechargeresult + "\n sign:"
				+ sign);
		boolean flag = checkData(merchantid, orderno, orderstatus,
				rechargetime, sign, resp, rechargeresult);
		if (flag) {
			try {
				SocketDTO dto = sendMsg(merchantid, orderno, orderstatus,
						rechargetime, sign, rechargeresult, req);
				Head head = dto.getHead();
				String resCode = head.getResponseCode();
				if (Constant.SUCCESS.equals(resCode)) {
					resp.getWriter().write("Success");
					close(resp.getWriter());
				} else {
					resp.getWriter().write("未知错误!");
					close(resp.getWriter());
				}
			} catch (Exception e) {
				resp.getWriter().write("未知错误!");
				close(resp.getWriter());
			}
		}
	}

	/**
	 * 发送消息给service
	 * 
	 * @param merchantid
	 * @param orderno
	 * @param orderstatus
	 * @param rechargetime
	 * @param sign
	 * @param rechargeresult
	 * @param req
	 * @return
	 */
	private SocketDTO sendMsg(String merchantid, String orderno,
			String orderstatus, String rechargetime, String sign,
			String rechargeresult, HttpServletRequest req) {
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode("020996");
		head.setIp(IpUtil.getIpAddr(req));
		head.setUserId("0");

		EnfuServerInfo info = new EnfuServerInfo();
		info.setMerchantid(merchantid);
		info.setOrderno(orderno);
		info.setOrderstatus(orderstatus);
		info.setRechargetime(rechargetime);
		info.setRechargeresult(rechargeresult);
		return super.send(head, info);
	}

	/**
	 * 
	 * @param merchantid
	 * @param orderno
	 * @param orderstatus
	 * @param rechargetime
	 * @param sign
	 * @param resp
	 * @param rechargeresult
	 * @return
	 * @throws IOException
	 */
	private boolean checkData(String merchantid, String orderno,
			String orderstatus, String rechargetime, String sign,
			HttpServletResponse resp, String rechargeresult) throws IOException {
		boolean flag = false;
		if (StringUtils.isEmpty(merchantid)) {
			resp.getWriter().write("缺少必要参数[merchantid]!");
			close(resp.getWriter());
			return false;
		} else if (StringUtils.isEmpty(orderno)) {
			resp.getWriter().write("缺少必要参数[orderno]!");
			close(resp.getWriter());
			return false;
		} else if (StringUtils.isEmpty(orderstatus)) {
			resp.getWriter().write("缺少必要参数[orderstatus]!");
			close(resp.getWriter());
			return false;
		} else if (StringUtils.isEmpty(rechargetime)) {
			resp.getWriter().write("缺少必要参数[rechargetime]!");
			close(resp.getWriter());
			return false;
		} else if (StringUtils.isEmpty(sign)) {
			resp.getWriter().write("缺少必要参数[sign]!");
			close(resp.getWriter());
			return false;
		} else {
			String signStr = getSign(merchantid, orderno, orderstatus,
					rechargetime, sign, rechargeresult);
			if (sign.equals(signStr)) {
				flag = true;
			} else {
				resp.getWriter().write("签名验证失败!");
				close(resp.getWriter());
				return false;
			}
		}

		return flag;
	}

	/**
	 * 生成签名字符串
	 * 
	 * @param merchantid
	 * @param orderno
	 * @param orderstatus
	 * @param rechargetime
	 * @param sign
	 * @param rechargeresult
	 * @return
	 */
	private String getSign(String merchantid, String orderno,
			String orderstatus, String rechargetime, String sign,
			String rechargeresult) {
		String md5key = PropertiesUtil.getValue("enfu.md5.key").trim();
		StringBuilder sb = new StringBuilder();
		sb.append(merchantid);
		sb.append(orderno);
		sb.append(orderstatus);
		sb.append(rechargeresult);
		sb.append(rechargetime);
		sb.append(md5key);

		String data = sb.toString().trim();
		String signStr = UtilMD5Encryption.createMD5StringOfGB2312(data);
		signStr = signStr.toLowerCase();
		return signStr;
	}

	/**
	 * 关闭资源
	 * 
	 * @param pw
	 */
	private void close(PrintWriter pw) {
		if (pw != null) {
			pw.flush();
			pw.close();
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

}
